package com.acme.service.bank;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import com.acme.domain.bank.Bank;
import com.acme.domain.bank.Client;
import com.acme.exceptions.AccountClosedException;
import com.acme.exceptions.ClientDuplicateException;
import com.acme.exceptions.ClientNotExistException;
import com.acme.exceptions.InjuredFileException;
import com.acme.exceptions.NotEnoughFundsException;

public class BankService {
	
	public static void addClient(Bank bank, Client client) throws ClientDuplicateException, ClientNotExistException {
		bank.addClient(client);
	}
	
	public static void modifyBank(Bank bank, int clientId, int accountId, double changeAmount) throws NotEnoughFundsException, ClientNotExistException, AccountClosedException {
		if(changeAmount >= 0) {
			bank.getClient(clientId).getAccount(accountId).deposit(changeAmount);
		} else {
			bank.getClient(clientId).getAccount(accountId).withdraw(-changeAmount);
		}
	}
	
	public static Client getClient(Bank bank, int id) throws ClientNotExistException {
		return bank.getClient(id);
	}
	
	public static void saveBank (Bank bank) throws IOException, ClientNotExistException {
		FileOutputStream fos = new FileOutputStream("bank.txt");
		ObjectOutputStream oos = new ObjectOutputStream(fos);
		for (Client client : bank.getClientsList()) {
				oos.writeObject(client);
		}
		oos.close();
		fos.close();
	}
	
	@SuppressWarnings("null")
	public static void loadBank (final Bank bank, final String path) throws IOException, ClassNotFoundException, ClientDuplicateException, ClientNotExistException {
		FileInputStream fis = new FileInputStream(path);
		ObjectInputStream ois = new ObjectInputStream(fis);
		while(ois != null) {
			bank.addClient((Client) ois.readObject());
		}
		ois.close();
		fis.close();
	}
	
	public static void loadClients(final Bank bank, final String path) throws IOException, InjuredFileException, NumberFormatException, ClientDuplicateException, ClientNotExistException {
		FileInputStream fstream = new FileInputStream(path);
		DataInputStream in = new DataInputStream(fstream);
		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		String temp;
		while((temp = br.readLine()) != null) {
			bank.addClient(temp);
		}
		br.close();
		in.close();
		fstream.close();
	}
}
